#include "rgaresourcemanager.h"

RgaResourceManager::RgaResourceManager(QObject *parent) : QObject(parent) {}

RgaResourceManager::~RgaResourceManager()
{
    release();
}

bool RgaResourceManager::initialize(int dma_fd, int width, int height, char *dst_buf)
{
    release(); // 先释放旧资源

    // 创建源缓冲区句柄
    src_handle = importbuffer_fd(dma_fd, width, height, RK_FORMAT_YCbCr_420_SP);
    if (!src_handle) {
        qCritical("源缓冲区创建失败");
        return false;
    }

    // 创建目标缓冲区句柄
    dst_handle = importbuffer_virtualaddr(dst_buf, width * height * 3);
    if (!dst_handle) {
        qCritical("目标缓冲区创建失败");
        releasebuffer_handle(src_handle);
        return false;
    }

    // 包装缓冲区
    src_buffer = wrapbuffer_handle(src_handle, width, height, RK_FORMAT_YCbCr_420_SP);
    dst_buffer = wrapbuffer_handle(dst_handle, width, height, RK_FORMAT_RGB_888);

    return true;
}

void RgaResourceManager::release()
{
    if (src_handle) {
        releasebuffer_handle(src_handle);
        src_handle = 0;
    }
    if (dst_handle) {
        releasebuffer_handle(dst_handle);
        dst_handle = 0;
    }
}

rga_buffer_t *RgaResourceManager::getSrcBuffer()
{
    return &src_buffer;
}

rga_buffer_t *RgaResourceManager::getDstBuffer()
{
    return &dst_buffer;
}
